package api

import (
	"go-weiqi-system/config"
	"go-weiqi-system/internal/models"
	"go-weiqi-system/internal/utils"

	"github.com/gin-gonic/gin"
)

type CompetitionController struct{}

// Index 比赛列表
func (ctrl *CompetitionController) Index(c *gin.Context) {
	var param models.PageParam
	if err := c.ShouldBindQuery(&param); err != nil {
		param.Page = 1
		param.PageSize = 10
	}

	keyword := c.Query("keyword")
	status := c.Query("competition_status")

	var competitions []models.Competition
	var total int64

	db := config.DB.Model(&models.Competition{}).Where("status = ?", 1)

	if keyword != "" {
		db = db.Where("title LIKE ?", "%"+keyword+"%")
	}
	if status != "" {
		db = db.Where("competition_status = ?", status)
	}

	db.Count(&total)
	db.Order("sort desc, id desc").
		Offset(param.GetOffset()).
		Limit(param.GetPageSize()).
		Find(&competitions)

	utils.Success(c, models.PageResponse{
		List:     competitions,
		Total:    total,
		Page:     param.GetPage(),
		PageSize: param.GetPageSize(),
	})
}

// Detail 比赛详情
func (ctrl *CompetitionController) Detail(c *gin.Context) {
	id := c.Query("id")
	if id == "" {
		utils.Error(c, "参数错误")
		return
	}

	var competition models.Competition
	if err := config.DB.Where("status = ?", 1).First(&competition, id).Error; err != nil {
		utils.Error(c, "比赛不存在")
		return
	}

	utils.Success(c, competition)
}
